package mobi.weq.servlets.user;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import mobi.weq.dao.UserDao;
import mobi.weq.model.User;
import mobi.weq.util.Util;

/**
 * Servlet implementation class RegisterUser
 */
@WebServlet("/user/login")
public class LoginUser extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		User user = null;
		if (username != null && password != null) {
			UserDao ud = new UserDao();
			try {
				user = ud.getUserByUsernamePassword(username, password);
				HttpSession session = request.getSession(true);
				session.setAttribute("user", user);

			} catch (SQLException e) {
				System.out.println(e);
			}
		}

		if (user != null) {
			Util.goHome(request, response);
		} else {
			response.sendRedirect("../login?errorMessage=Wrong username or password");
		}
	}

}
